// Physical memory allocator, for user processes,
// kernel stacks, page-table pages,
// and pipe buffers. Allocates whole 4096-byte pages.

#include "types.h"
#include "param.h"
#include "memlayout.h"
#include "spinlock.h"
#include "riscv.h"
#include "defs.h"
// void freerange(void *pa_start, void *pa_end, struct kmem current);
// void mykfree(void *pa, struct kmem current);

extern char end[]; // first address after kernel.
                   // defined by kernel.ld.

struct run {
  struct run *next;
};

struct kmem{
  struct spinlock lock;
  struct run *freelist;
};
//amendment of lock
struct kmem kmems[NCPU];//NCPU=8
void freerange(void *pa_start, void *pa_end);
void mykfree(void *pa, int current);


void
kinit()
{
  // initlock(&kmem.lock, "kmem");
  // freerange(end, (void*)PHYSTOP);
  // char str[6] = "kmem0";
  for (int i = 0; i < NCPU; ++i){
    initlock(&kmems[i].lock, "kmem");
  }
  freerange(end, (void*)PHYSTOP);
}

// void
// freerange(void *pa_start, void *pa_end)
// {
//   char *p;
//   p = (char*)PGROUNDUP((uint64)pa_start);
//   for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE)
//     kfree(p);
// }

void
freerange(void *pa_start, void *pa_end)
{ 
  char *p;
  p = (char*)PGROUNDUP((uint64)pa_start);
  int list_length = ((char*)pa_end - p) / (NCPU * PGSIZE);
  for(int i = 0; i < NCPU; ++i){
    int cnt = 0;
    for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE){
      mykfree(p, i);
      cnt++;
      if(cnt >= list_length){
        p+=PGSIZE;
        break;
      }
    }

  }
  
}

void
mykfree(void *pa, int current)
{
  struct run *r;

  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP){
    if(((uint64)pa % PGSIZE) != 0){
      panic("my kfree");
    }else{
      panic("out of range");
    }
  }
    

  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);

  r = (struct run*)pa;

  acquire(&kmems[current].lock);
  r->next = kmems[current].freelist;
  kmems[current].freelist = r;
  release(&kmems[current].lock);
}

void steal(int curr_cpu){
  for (int i = 0; i < NCPU; ++i){
    if(i == curr_cpu) continue;
    else{
      acquire(&kmems[i].lock);
      if(kmems[i].freelist){
        struct run * temp = kmems[i].freelist;
        kmems[i].freelist = temp->next;
        release(&kmems[i].lock);
        temp->next = (void*)0;
        kmems[curr_cpu].freelist = temp;
        break;
      }
      release(&kmems[i].lock);
    }
  }
}

// Free the page of physical memory pointed at by v,
// which normally should have been returned by a
// call to kalloc().  (The exception is when
// initializing the allocator; see kinit above.)


void
kfree(void *pa)
{
  struct run *r;

  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
    panic("kfree");

  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);

  r = (struct run*)pa;

  push_off();
  int id = cpuid();
  pop_off();

  acquire(&kmems[id].lock);
  r->next = kmems[id].freelist;
  kmems[id].freelist = r;
  release(&kmems[id].lock);
}

// Allocate one 4096-byte page of physical memory.
// Returns a pointer that the kernel can use.
// Returns 0 if the memory cannot be allocated.
void *
kalloc(void)
{
  struct run *r;

  push_off();
  int id = cpuid();
  pop_off();

  acquire(&kmems[id].lock);
  r = kmems[id].freelist;
  if(r)
    kmems[id].freelist = r->next;
  else{
    steal(id);
    r = kmems[id].freelist;
    if(r)
      kmems[id].freelist = r->next;
  }
  release(&kmems[id].lock);

  if(r)
    memset((char*)r, 5, PGSIZE); // fill with junk
  return (void*)r;
}
